package com.wanmait.movie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.movie.common.HttpCode;
import com.wanmait.movie.constant.UserContsant;
import com.wanmait.movie.entity.User;
import com.wanmait.movie.entity.request.user.UserLoginRequest;
import com.wanmait.movie.entity.request.user.UserRegisterRequest;
import com.wanmait.movie.mapper.UserMapper;
import com.wanmait.movie.service.UserService;
import com.wanmait.movie.util.AjaxResult;
import com.wanmait.movie.util.JWTUtils;
import com.wanmait.movie.util.RegxUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: UserServiceImpl
 * Package: com.wanmait.movie.service.impl
 * Description:
 *
 * @Author Fengxd
 * @Create 2023/12/5 10:53
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService  {
    @Resource
    private UserMapper userMapper;
    @Override
    public AjaxResult register(UserRegisterRequest userRegisterRequest) {
        // region 获取用户注册信息
        String username = userRegisterRequest.getUsername();
        String password = userRegisterRequest.getPassword();
        String confirmPassword = userRegisterRequest.getConfirmPassword();
        String phone = userRegisterRequest.getPhone();
        String email = userRegisterRequest.getEmail();
        // endregion
        // region 参数不能为空
        if (!StringUtils.hasLength(username)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"用户名为空");
        }
        if (!StringUtils.hasLength(password)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"密码为空");
        }
        if (!StringUtils.hasLength(confirmPassword)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"确认密码为空");
        }
        if (!StringUtils.hasLength(phone)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"手机号为空");
        }
        if (!StringUtils.hasLength(email)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"邮箱为空");
        }
        // endregion
        // region 用户名（5-20位/用于登录和发表评论/唯一）
        LambdaQueryWrapper<User> usernameQueryWrapper = new LambdaQueryWrapper<>();
        usernameQueryWrapper.eq(User::getUsername, username);
        if (userMapper.selectCount(usernameQueryWrapper) > 0) {
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"用户名已存在");
        }
        if (username.length() < 5 || username.length() > 20) {
            AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"用户名长度5-20位");
        }
        if (username.contains(" ")){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"用户名不能包含空格");
        }
        // endregion
        // region 密码（8-15位）
        if (password.length() < 8 || password.length() > 15) {
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"密码长度8-15位");
        }
        // endregion
        // region 确认密码（两次密码一致）
        if (!password.equals(confirmPassword)) {
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"两次密码不一致");
        }
        // endregion
        // region 手机号（11位/可用于登录/唯一）
        LambdaQueryWrapper<User> phoneQueryWrapper = new LambdaQueryWrapper<>();
        phoneQueryWrapper.eq(User::getPhone, phone);
        if (userMapper.selectCount(phoneQueryWrapper) > 0){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"手机号已存在");
        }
        if (!RegxUtil.regexChecking(UserContsant.PHONE_REGEX,phone)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"手机号格式错误");
        }
        // endregion
        // region 邮箱（可用于找回密码/唯一/需要验证邮箱格式）
        LambdaQueryWrapper<User> emailQueryWrapper = new LambdaQueryWrapper<>();
        emailQueryWrapper.eq(User::getEmail,email);
        if (userMapper.selectCount(emailQueryWrapper) > 0){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"邮箱已存在");
        }
        if (!RegxUtil.regexChecking(UserContsant.EMAIL_REGEX,email)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(), "邮箱格式错误");
        }
        // endregion
        // region 添加用户信息
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setEmail(email);
        if (!this.save(user)){
            return AjaxResult.error(HttpCode.SYSTEM_ERROR.getCode(),"注册失败，" + HttpCode.SYSTEM_ERROR.getMsg());
        }
        return AjaxResult.success("注册成功");
        // endregion
    }

    @Override
    public AjaxResult login(UserLoginRequest userLoginRequest, HttpServletRequest request) {
     String account = userLoginRequest.getAccount();
     String password = userLoginRequest.getPassword();
        // region 参数不能为空
        if (!StringUtils.hasLength(account)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"账号为空");
        }
        if (!StringUtils.hasLength(password)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"密码为空");
        }
        // endregion
        // region 用户登录
        LambdaQueryWrapper<User> userLoginQueryWrapper = new LambdaQueryWrapper<>();
        userLoginQueryWrapper.eq(User::getPassword,password);
        // 是否使用手机号登录
        if (RegxUtil.regexChecking(UserContsant.PHONE_REGEX,account)){
            userLoginQueryWrapper.eq(User::getPhone,account);
        }else {
            userLoginQueryWrapper.eq(User::getUsername,account);
        }
        User user = userMapper.selectOne(userLoginQueryWrapper);
        if (user == null){
            return AjaxResult.error(HttpCode.LOGIN_FAILED.getCode(), HttpCode.LOGIN_FAILED.getMsg());
        }
        // 隐藏密码
        user.setPassword(null);
        // 载荷
        Map<String,String> claims = new HashMap<>();
        claims.put("id",user.getId().toString());
        claims.put("roles","user");
        // 登录信息
        request.getSession().setAttribute("user",user);
        // 生成token
        String token = JWTUtils.createToken(user.getId().toString(), UserContsant.EXPIRES_MINUTES, UserContsant.SECRET_KEY, claims);
        return AjaxResult.success("登录成功",user).put("token",token);
        // endregion
    }

    @Override
    public PageInfo<User> getUserList(String keyword, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(keyword!=null){
            queryWrapper.like(User::getUsername,keyword).or().like(User::getEmail,keyword).or().like(User::getPhone,keyword);
        }
        List<User> users = userMapper.selectList(queryWrapper);
        return  new PageInfo<>(users);
    }
}
